import React, { PureComponent,Fragment } from "react";
import { connect } from "dva";
import moment from "moment";
import { Row, Col, Card, Icon, Button, Dropdown, Popconfirm, message, Divider, Form, Input} from "antd";
import StandardTable from '../../../components/StandardTable';
import Authorized from '../../../utils/Authorized';
import styles from '../../Pbulic.less';
const FormItem = Form.Item;

const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');

@connect(({ repository, global }) => ({
  baseUrl:global.baseUrl,
  resdata: repository.resdata,
  loading: repository.loading,
  // loading: loading.models.equipment_integrated,
}))
@Form.create()
export default class ListTable extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      currentPage: 1,
      pageSize: 10,
      selectedRows: [],
      formValues: {},
    };
  }



  componentDidMount() {
    const { pageSize } = this.state;
    const { pagesquery } = this.props;
    // 列表
    this.getDataList(pagesquery,pageSize,1);
  }

  componentWillReceiveProps(nextProps) {
    // 外层发起刷新数据请求
    if ((nextProps.isReloadList === true && this.props.isReloadList === false) || (nextProps.fileFolder !== this.props.fileFolder)) {
      const { pageSize } = this.state;
      this.getDataList({},pageSize,1);
      this.props.sotpReloadList();
    }
  }


  getDataList(params,pageSize,currentPage) {
    const { dispatch, fileFolder } = this.props;
    dispatch({
      type: 'repository/fetch_repository_list',
      payload: {
        pageSize,
        currentPage,
        // ...pagesquery,
        ...params,
        fileFolder,
      },
    });
  }

  // 分页、排序、筛选变化时触发
  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues,pageSize } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      // currentPage: pagination.current,
      // pageSize: pagination.pageSize,
      ...formValues,
      ...filters,
    };

    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    this.setState({
      currentPage:pagination.current
    },()=>{
      this.getDataList(params,pageSize,pagination.current);
    })

  };

  // 重置表单
  handleFormReset = () => {
    const { form } = this.props;
    const {pageSize,currentPage} = this.state;
    //form.resetFields();
    form.setFieldsValue({
      fileTitle:undefined,
      keyword:undefined,
    })
    this.setState({
      formValues: {},
    });
    this.getDataList({},pageSize,1);
  };


  // 表格复选框选中
  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows.map(item => item.repositoryId),
    });
  };

  // 表单搜索
  handleSearchSubmit = e => {
    e.preventDefault();

    const { form } = this.props;
    const { pageSize } = this.state;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      this.setState({
        formValues: fieldsValue,
      });

      this.getDataList(fieldsValue,pageSize,1);
    });
  };



  // 批量删除
  handleActionList = (type,id) => {
    const { dispatch } = this.props;
    const { selectedRows,formValues, pageSize, currentPage } = this.state;
    if(!id && !selectedRows) return;
    const repositoryId= id ? [id] : selectedRows;

    switch (type) {
      case '3':
        dispatch({
          type: 'repository/action_repository_del',
          payload: {
            repositoryId,
          },
        }).then(()=>{
          this.setState({
            selectedRows: [],
          });
        }).then(()=>{
          message.success("所选文件已删除")
        }).then(()=>{
          this.getDataList(formValues,pageSize,currentPage);
        });
        break;
      case '4':
        dispatch({
          type: 'repository/action_repository_export',
          payload: {
            repositoryId,
          },
        }).then(()=>{
          this.setState({
            selectedRows: [],
          });
        }).then(()=>{
          message.success("文件导出成功")
        });
        break;

      default:

        break;
    }
  };

  // 批量导入
  handleBatchImport = info => {
    let fileList = info.fileList;
    const { dispatch } = this.props;
    const { formValues,pageSize } = this.state;

    if (info.file.status == "done") {
      fileList = fileList.map(item => {
        if (item.response && item.response.error_no != "0") {
          item.status = "error";
        }
        return item;
      });


      if(info.file && info.file.response && info.file.response.data && info.file.response.data.token){
        dispatch({
          type: 'repository/action_repository_import',
          payload: {
            file_url:info.file.response.data.token,
          },
        }).then(()=>{
          message.success("文件导入成功")
        }).then(()=>{
          this.getDataList(formValues,pageSize,1);
        });
      }

    }


  };

  // 新增model传导-------------------
  handleAddModel = (e) =>{
    this.props.addModelCallBack(e);
  }

  // 查看文件，进行文件下载操作
  handleFileDownload= (detailInfoId,filePath) =>{


  }

  // 移动model传导
  handleRepositoryMoveModel= (ids) =>{
    this.props.repositoryMoveModelCallBack(ids);
  }

  // 搜索内容
  renderSearchForm() {
    const { form, pagesquery } = this.props;
    const { getFieldDecorator } = form;
    return (
      <Form onSubmit={this.handleSearchSubmit} >
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={6} sm={24}>
            <FormItem label="文档名称">
              {getFieldDecorator('fileTitle',{
                initialValue: pagesquery && pagesquery.fileTitle ? pagesquery.fileTitle : undefined,
              })(<Input placeholder="请输入文档名称" />)}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <FormItem label="关键字">
              {getFieldDecorator('keyword',{
                initialValue: pagesquery && pagesquery.keyword ? pagesquery.keyword : undefined,
              })(<Input placeholder="请输入关键字" />)}
            </FormItem>
          </Col>


          <Col md={6} sm={24}>
            <div style={{ float: 'right', marginBottom: 24 }}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
                重置
              </Button>
            </div>
          </Col>

        </Row>
      </Form>
    );
  }


  render() {

    const { resdata, loading, baseUrl, fileFolder } = this.props;
    const { selectedRows } = this.state;


    const columns = [
      {
        title: '序号',
        dataIndex: 'no',
        fixed: 'left',
        render: (text, row, index)=> (
          <span>{index+1}</span>
        ),
      },
      {
        title: '文档编号',
        dataIndex: 'fileCode',
      },
      {
        title: '文档名称',
        dataIndex: 'fileTitle',
      },
      {
        title: '关键字',
        dataIndex: 'keyword',
      },
      {
        title: '创建人',
        dataIndex: 'creator',
      },
      {
        title: '创建时间',
        dataIndex: 'createTime',
        render: text => moment(text).format("YYYY-MM-DD HH:mm")
      },
      {
        title: '备注',
        dataIndex: 'remarks',
      },
      {
        title: '操作',
        render: (text, row, index) => (
          <a href={`${baseUrl}${row.fileUrl}`} target="_blank">下载</a>

        ),
      },
    ];
    {/*<a onClick={() => this.handleFileDownload(row.repositoryId, row.filePath)}>下载</a>*/}



    return (
      <Card bordered={false}>
        <div className={styles.tableList}>
          <div className={styles.tableListForm}>{this.renderSearchForm()}</div>
          <div className={styles.tableListOperator}>
            <Authorized authority={`${10262 + Number(fileFolder-1)*10}`} >
              <Button icon="plus" type="primary"  onClick={() => this.handleAddModel(0)}>
                新建
              </Button>
            </Authorized>
            {/*
              <Upload showUploadList={false} onChange={this.handleBatchImport}>
                <Button icon="plus" type="primary" >
                  批量导入
                </Button>
              </Upload>
            */}

            <Authorized authority={`${10264 + Number(fileFolder-1)*10}`}>
              <Popconfirm title="是否确定要批量删除?" onConfirm={() => this.handleActionList("3")}  okText="是" cancelText="否">
                <Button icon="minus" type="default" disabled={selectedRows.length > 0 ? false : true}>
                  批量删除
                </Button>
              </Popconfirm>
            </Authorized>
            <Authorized authority={`${10263 + Number(fileFolder-1)*10}`}>
              <Button type="default" onClick={() => this.handleRepositoryMoveModel(selectedRows)} disabled={selectedRows.length > 0 ? false : true}>
                移动
              </Button>
            </Authorized>
{/*            <Authorized  authority={`${10265 + Number(fileFolder-1)*10}`}>
              <Button type="default" onClick={() => this.handleActionList("4")} disabled={selectedRows.length > 0 ? false : true}>
                导出
              </Button>
            </Authorized>*/}

          </div>
          <StandardTable
            selectedRows={selectedRows}
            rowKey="repositoryId"
            // scroll={{ x: 1500 }}
            loading={loading.reslist}
            data={resdata}
            columns={columns}
            onSelectRow={this.handleSelectRows}
            onChange={this.handleStandardTableChange}
          />
        </div>
      </Card>

    );
  }
}
